package org.dreamwork.cai.io.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import org.dreamwork.cai.io.impl.RouteBroadcastProcessor;
import org.dreamwork.cai.proxy.IServiceResolver;

import java.net.InetSocketAddress;

public class NettyUDPReceiver extends SimpleChannelInboundHandler<DatagramPacket> {
    private final int senderPort;

    private final IServiceResolver resolver;

    public NettyUDPReceiver (IServiceResolver resolver, int senderPort) {
        this.resolver   = resolver;
        this.senderPort = senderPort;
    }

    @Override
    protected void channelRead0 (ChannelHandlerContext ctx, DatagramPacket packet) {
        InetSocketAddress remoteAddress = packet.sender ();
        if (!RouteBroadcastProcessor.checkAddress (remoteAddress, senderPort)) {
            return;
        }

        byte[] buff = NettyHelper.toBytes (packet.content ());
        RouteBroadcastProcessor.handle (buff, 0, buff.length, resolver, remoteAddress);
    }
}